define(function (require, exports, module) {
    // require('./plug/hammer.min');
    // require('./plug/swiper.jquery.min');
    // require('./plug/lazyload_echo');
    // require('./plug/layer/layer');
    // require('./shop');
    var myPub = require('./public');

    var oFooter = $('.js_footer');              //底部
    var oContain = $('.js_contain');			//主体
    var oShadow = $('.js_shadow');				//阴影
    var oServerMain = $('.js_serverMain');		//服务说明内容
    var oServerList = $('.js_serverList');		//产品服务信息列表
    var oServer_button = $('.js_server_button');  //服务说明确定按钮

    var oWindowH = $(window).height();
    var oGoods_showThree = $('.js_goods_showThree');	//三排产品

    var oCloseSideBtn = $('.js_closeSideBtn'); 	//详情关闭按钮

    var oSellMemberId = $('#sellMemberId'); //丰享sellMemberId


    // add  by xiechagnwen 当家爆款
    var oGoods_showTwo = $('.js_goods_showTwo');	//并排产品
    var oHScroll = $('.js_HScroll');		//水平滚动 导航和产品
    var oHScroll_Ul = oHScroll.find('ul');
    var oHScroll_Li = oHScroll.find('li');

    SetUlWidth();
    $(window).resize(function() { SetUlWidth(); });

    //水平滚动
    oHScroll.on('scroll',function() {
        //水平懒加载
        myPub.throttle(myPub.lazLoadingImgEcho, window);
        //设置水平滚动位置
        sessionStorage.setItem("goodsdetail_oHScroll", oHScroll.scrollLeft());
    });

    //设置并排产品的图片高度
    myPub.SetImgHeight(oGoods_showTwo);

    function SetUlWidth() {
        //水平滚动li的宽度
        var oHScroll_Li_W = oHScroll_Li.outerWidth(true);
        oHScroll_Ul.css({
            'width' : oHScroll_Li_W * oHScroll_Li.length
        });
    }
    HistoryX();
    //水平定位
    function HistoryX() {
        if(sessionStorage.getItem('goodsdetail_oHScroll') !== null) {
            var _HDis = parseInt( sessionStorage.getItem('goodsdetail_oHScroll') )
            oHScroll.scrollLeft( _HDis )
        }

    }
    // end  by xiecahgnwen

    var minNum = 1;
    var minCount = $('.jsMinCount');
    if(minCount.attr("minCount") != null && minCount.attr("minCount") != undefined){
        minNum = parseInt(minCount.attr("minCount"));
    }

    //取消滑动
    oFooter.on("touchmove", function (e) {
        e.preventDefault()
    });
    oShadow.on("touchmove", function (e) {
        e.preventDefault()
    });


    //产品懒加载  异步加载 调用这个
    myPub.lazLoadingImgEcho();

    myPub.SetImgHeight(oGoods_showThree);




    var moveHeight = oServerMain.outerHeight(true);
    oServerMain.css({'bottom': -moveHeight});

    //显示产品服务信息
    oServerList.hammer().on('tap', function (e) {
        myPub.OffMuiEvent(false);
        oServerMain.show().stop().animate({'bottom': 0}, 300, function () {
            oShadow.show();
        });
        myPub.HamstopPropaga();
        $(document).on('touchmove', function (e) {
            e.preventDefault();
        });
    });

    //产品服务确定按钮
    oServer_button.hammer().on('tap', function (e) {
        oServerMain.stop().animate({bottom: -moveHeight}, 300, function () {
            oServerMain.hide();
            oShadow.hide();
            myPub.OffMuiEvent(true);
        });
        $(document).off('touchmove');
        myPub.HamstopPropaga()
    });


    //选择规格 oWindowH
    var oWrap = $('.js_wrap'); 						//主题页面
    var oSeletSide = $('.js_seletSide');			// 产品规格页面
    var oGoodsSizeList = $('.js_goodsSizeList');//产品规格列表
    var oGoodsList = $('.js_goodsList');//产品规格列表
    var ogoodsSizeListTow = $('.js_goodsSizeListTow'); //鲜花规格多选
    var oGoodsSizeFlowers = $('.js_goodsSizeFlowers');
    var oAddCarBtn = $('.js_addCarBtn');			//加入购物车和立即购买按钮
    var oUser_seleted = $('.js_user_seleted');		//用户规格选择
    var _scrollTop;
    var off_goPage;									//加入购物车和立即购买判断参数
    var oAddCarOKBtn = $('.js_addCarOKBtn');//产品规格确定按钮
    var oAddCarONBtn = $('.js_addCarONBtn');//产品规格可选择数量按钮
    var oAddCarONBtnNum = $('.js_addCarONBtn i').html();//产品规格可选择数量
    var oSumNum = $('.js_sumNum');		//规格输入框

    var oAddBtnDistable = oAddCarBtn.eq(0).attr('enableButton');

	if(oAddBtnDistable == 'false'){
		oAddCarBtn.eq(0).removeClass('btn_BorderRed').addClass('btnDistable');
	}



    oAddCarBtn.hammer().on('tap', function (e) {
        //oAddCarBtn.on('click',function(e) {
        //获取浏览记录
        /*
         _scrollTop = $(window).scrollTop();
         $('body').css({'height': oWindowH, 'overflow':'hidden'});
         oWrap.addClass('scaleStyle').css({'top': -_scrollTop})
         */

        myPub.OffMuiEvent(false);

        var index = oAddCarBtn.index($(this));
        switch (index) {
            //加入购物车
            case 0 :
                if(oAddBtnDistable == 'false') {
                	myPub.TipLayer("本商品不能加入购物车,请点击立即购买~");
					return false;
				}

                off_goPage = true;
                break;

            //立即购买
            case 1 :
                off_goPage = false;
                break;
        }


        oSeletSide.show().stop().animate({'bottom': 0}, 300, function () {
            oShadow.show();
        });
        $(document).on('touchmove', function (e) {
            e.preventDefault();
        });
        oGoodsSizeList.find('.js_goodsSize').on('touchmove', function (e) {
            e.stopPropagation();
        });


        oGoodsSizeList.find('li').each(function(i){
			if(oGoodsSizeList.find('li').eq(i).attr('mutliStore') == "0") {
				oGoodsSizeList.find('li').eq(i).addClass('color_Distable')
			}
			else {
				oGoodsSizeList.find('li').eq(i).removeClass('color_Distable')
			}
		});

        myPub.HamstopPropaga();
    });

	var map = {};   		//获取多规格信息
	var list = [];			//获取鲜花规格
    var chooseCount = 0;	//用户选择的规格个数
    var productIds = [];	//用户选择规格的 productId 数组

    oGoodsSizeList.hammer().on('tap', function (e) {
        myPub.OffMuiEvent(false);
        var _tar = e.gesture.target;
    	var target;
    	var bAct_MoreSize = $(this).hasClass('active_moreSize'); 		//多维度
    	var bAct_FlowerSize = $(this).hasClass('active_flowerSize'); 	//鲜花多规格

    	//_tar.nodeName.toLowerCase() == 'li' ? target = $(_tar) : target = $(_tar).parents('li');

    	if(_tar.nodeName.toLowerCase() == 'li') {
    		target = $(_tar)
	    	//选择库存为0的产品
	    	if(target.attr('mutliStore')==0) {
	            return false;
	        }

	    	//多维度
	    	if(bAct_MoreSize) {

	    		//获取当前点击li的父级下面的所有li并删除class上的active
	    		target.parents('.js_goodsSizemob').find('li').removeClass('active');
	    		//添加active
	    		target.addClass('active');

				//获取当前点击的li的父级ID
	            var spanId = target.parents('.js_goodsSizemob').attr('id');
	            //用父级id为KEY（键）获取选中的内容；
	            map[spanId] = target.text();
	            var stringLi = $.map(map, function(n){
	            	//便利map
	                return n;
	            }).join(",");//拼接字符串
	            oUser_seleted.find('span').text(stringLi);

	            var specIndex = target.parents('.js_goodsSizemob').attr("id");
	            iavPath = "";//使用前初始化
	            changeSpecProductSize(target,specIndex);


	    	}
	    	//鲜花多规格
	    	else if(bAct_FlowerSize) {
	    		//弹起规格时 将没有库存的规格灰显
				if (target.hasClass('active')) {
		            target.removeClass('active');

		            $.each(list, function (i) {
		                var objLi = list[i];
		                if (!$(objLi).hasClass('active')) {
		                    list.arrayRemove(i);
		                    i = oAddCarONBtnNum - list.length;
		                    oAddCarONBtn.text('还可以选择' + i + '件');
		                    oAddCarONBtn.show()
							oAddCarOKBtn.hide();
		                }

		            });
		            return;
		        }
		        list.push(target);
		        target.addClass('active');
		        if (list.length > oAddCarONBtnNum) {
		            list.shift().removeClass('active');
		        }
		        i = oAddCarONBtnNum - list.length;
		        oAddCarONBtn.text('还可以选择' + i + '件');
		        if (i == 0) {
		            oAddCarONBtn.hide();
	                oAddCarOKBtn.show();
		        }

		        changeGoodsSize(target);

	    	}
	    	//正常产品
	    	else {
			 	var index = target.index();
	        	oGoodsSizeList.find('li').removeClass('active').eq(index).addClass('active');

	        	oUser_seleted.find('span').text(target.text());
	         	changeGoodsSize(target);
	    	}
	    }

        myPub.HamstopPropaga()
    });




    //花瓶需要否规格选择
    oGoodsSizeFlowers.hammer().on('tap', function (e) {
        myPub.OffMuiEvent(false);
        var _tarTag = e.gesture.target;
        var target;
        if (_tarTag.nodeName.toLowerCase() == 'li') {
            target = $(_tarTag);
            if(target.hasClass('active')){
                target.removeClass('active');
                return;
            }
            //oGoodsSizeFlowers.find('li').removeClass('active');
            target.addClass('active');
            changeGoodsSize(target);
        }
    });

    Array.prototype.arrayRemove = function (dx) {
        if (isNaN(dx) || dx > this.length) {
            return false;
        }
        this.splice(dx, 1);
    };


    //阴影关闭
    oShadow.hammer().on('tap', function (e) {
        //隐藏服务
        oServerMain.stop().animate({bottom: -moveHeight}, 300, function () {
            oServerMain.hide();
            oShadow.hide();
        });
        //隐藏规格
        oSeletSide.stop().animate({'bottom': '-85%'}, 300, function () {
            oSeletSide.hide();
            oShadow.hide();
        });
        myPub.OffMuiEvent(true);
        myPub.HamstopPropaga();
        $(document).off('touchmove');
    });

    //规格关闭按钮
    oCloseSideBtn.hammer().on('tap', function (e) {
        //隐藏服务
        oServerMain.stop().animate({bottom: -moveHeight}, 300, function () {
            oServerMain.hide();
            oShadow.hide();
        });
        //隐藏规格
        oSeletSide.stop().animate({'bottom': '-85%'}, 300, function () {
            oSeletSide.hide();
            oShadow.hide();
        });
        myPub.OffMuiEvent(true);
        myPub.HamstopPropaga();
        $(document).off('touchmove');
    });


    //产品规格确定按钮
    oAddCarOKBtn.hammer().on('tap', function (e) {
        // 无货状态无法点击
        if(tapFlag){
           return;
        }
        var kucun = $("#kucun").attr("value");
        /*if(off_goPage) {
         //检测是  加入购物车 按钮
         console.log('加入购物车')
         }
         else {
         //检测是 立即购买 按钮
         console.log('立即购买')
         //window.location.herf = ''
         }
         */
        //console.log(chooseCount);

        //当不是多选规格时  list是空的  也就是普通商品

        if(list.length != 0){
            chooseCount = list.length;
        }else{
            chooseCount = $(".js_choose").find("li.active").length;
        }

        //console.log(chooseCount);

        //多规格选择的校验
        if(checkSel() == false){
            return;
        }


        if (off_goPage) {


            var quantity = $("#quantity").val();
            if (kucun == 0) {
                myPub.TipLayer("该商品已经没有库存啦~");
                return;
            }
            //当商品不是多规格商品时需要校验用户是否选择了规格
            if(isSpecificationEnabled == false){
                if (chooseCount == 0 ) {
                    myPub.TipLayer("请选择商品规格！");
                    return;
                }
            }

            G_JSON_POST('/shop/cartItem/addCart', {"pId": selectedProductId, "quantity": quantity,"goodschannel":goodschannel}, function (data) {
                if (data.status == "success") {
                    var cartCount = data.cartCount;
                    //$("#cartCount").html(cartCount);
                    myPub.TipLayer('<span class="icon-rightIcon icon_myLayer"></span>加入购物车成功！');
                    oSeletSide.stop().animate({'bottom': '-85%'}, 300, function () {
                        oSeletSide.hide();
                        oShadow.hide();
                        myPub.OffMuiEvent(true)
                    });

                    $.ajax({
                        type: "POST",
                        url: "/shop/cartItem/getCount",
                        dataType: "json",
                        success: function (data) {
                            if (data.count != 0) {
                                $(".js_userNum").show();
                                $('.js_userNum').html(data.count);
                            } else {
                                $('.js_userNum').hide();
                            }
                        },
                        error: function (textStatus) {
                            if (textStatus.status == 403) {
                                $('.js_userNum').hide();
                            }
                        },
                        complete: function (XHR) {
                            XHR = null;
                        }
                    });
                } else {
                    myPub.TipLayer(data.message);
                }
            });
        }
        else {
            productIds = [];

            //多选商品
            $.each(list,function(i){
                var objLi = list[i];
                var tmpid = objLi.attr('id');
                //加入id数组
                productIds.push(tmpid);
            });

            //花瓶等附属商品
            oGoodsSizeFlowers.find("li.active").each(function(i){
                var temval = oGoodsSizeFlowers.find("li.active").eq(i).attr("id");
                productIds.push(temval);
            })

            myPub.ValiNum(oSumNum, function () {
                oAddCarOKBtn.attr('href', '#1');
            }, function () {
                var quantity = $("#quantity").val();
                if (kucun == 0) {
                    myPub.TipLayer("该商品已经没有库存啦~");
                    return;
                }
                /*if(idArrays.length>0){
                    for(var i=0;i<idArrays.length;i++){
                       var tmpId = oGoodsList.find("li.active").parents('.js_goodsSizemob').attr("id");
                       console.log(tmpId);
                    }
                    return;
                }*/
                //当商品不是多规格商品时需要校验用户是否选择了规格
                if(isSpecificationEnabled == false){
                    if (chooseCount == 0 ) {
                        myPub.TipLayer("请选择商品规格！");
                        return;
                    }
                }
                console.log(chooseCount);
                if(chooseCount > 1){
                    window.location.href = '/shop/pay/buynowMulti?productIds='+productIds;
                }else{
                    // console.log(oSellMemberId.val()+"fdsafdsa");
                    if(oSellMemberId.val()!=undefined){
                        window.location.href = '/shop/pay/buynow?productIdAndquantity='+selectedProductId+','+quantity+'&sellMemberId='+oSellMemberId.val();
                    }else{
                        window.location.href = '/shop/pay/buynow?productIdAndquantity='+selectedProductId+','+quantity+'&goodschannel='+goodschannel;
                        // window.location.href = '/shop/pay/buynow?productIdAndquantity='+selectedProductId+','+quantity;
                    }
                    // console.log("fdsafdsfds");
                    // window.location.href = '/shop/pay/buynow?productIdAndquantity='+selectedProductId+','+quantity;
                }


            });


        }
        oSeletSide.stop().animate({'bottom': '-85%'}, 300, function () {
            oSeletSide.hide();
            oShadow.hide();
            myPub.OffMuiEvent(true)
        });


        myPub.HamstopPropaga();
        $(document).off('touchmove');
    });

    function checkSel(){
        var obj = $('.js_goodsSizemob');
        var objLeng = $('.js_goodsSizemob[id]').length;
        for(var i=0; i<=objLeng-1;i++){
            var objP = $('.js_goodsSizemob[id ='+i+']  p').text();
            var objLi = $('.js_goodsSizemob[id ='+i+'] li');
            if(!objLi.hasClass('active')){
                myPub.TipLayer('请选择商品'+objP);
                return false;
            }
        }
    }

    //广告轮播
    var sTime = null;
    var oSilderImg = $('.js_silderImg');        //广告轮播框
    var oBNext = $('.js_BNext');                //下一个
    var oBPrev = $('.js_BPrev');                //上一个
    var oPagin = $('.js_pagin');                //个数点

    Swiper_indexAD();
    function Swiper_indexAD() {
        var indexSwiperAD = oSilderImg.swiper({
            nextButton: oBNext,
            prevButton: oBPrev,
            pagination: oPagin,
            paginationClickable: false,
            preloadImages: false,
            lazyLoading: true,
            autoplay: 4000,
            onTouchEnd: function (swiper) {
                clearTimeout(sTime);
                sTime = setTimeout(function () {
                    indexSwiperAD.startAutoplay();
                }, 4000);
            },
        });
    }



    function changeGoodsSize(activeSizeLi) {

        var $thisId = activeSizeLi.attr("id");
        if ($thisId == selectedProductId) {
            return false;
        }
        $("#quantity").val(minNum);
        selectedProductId = $thisId;
        $("#kucun").attr("value", productDatas[selectedProductId].store);
        $("#kucun").html(productDatas[selectedProductId].store);

        if($('#costMemberScore').length > 0){
            $("#salePrice").attr("pPrice", productDatas[selectedProductId].memberPrice);
            $("#salePrice").html(productDatas[selectedProductId].memberPrice);
            $("#costMemberScore").html(productDatas[selectedProductId].memberCostScore);
        }else {
            $("#salePrice").attr("pPrice", productDatas[selectedProductId].salePrice);
            $("#salePrice").html(productDatas[selectedProductId].salePrice);
        }
        if(productDatas[selectedProductId].imgPath != imgBasePath){
            $("#currentImg").attr("src", productDatas[selectedProductId].imgPath);
            $("#currentImg").html(productDatas[selectedProductId].imgPath);
        }


    }

    //获取多维度商品的售价和库存
    var tapFlag = false;
    var idArrays=[];
    var specLength = oneIavPth.split(",").length;//默认商品 iavpath剪切后的长度
    var iavPath = "";//product的iavPath属性
    function changeSpecProductSize(obj,index) {
        if(idArrays.length>=index){
            idArrays.splice(index,1,obj.val());
        }else{
            for(var i=0;i<index;i++){
                idArrays.push(0);
            }
            idArrays.splice(index,1,obj.val());
        }
        console.log(idArrays);
        //当规格值选择完毕时  显示售价及其库存

        if(idArrays.length == specLength && ($.inArray(0,idArrays) == -1)){
            //拼接选中的规格 id
            for(var i=0;i<idArrays.length;i++){
                if(i<idArrays.length-1){
                    iavPath += idArrays[i]+",";
                }else{
                    iavPath += idArrays[i];
                }

            }


            //console.log(iavPathArrays);
            //当iavPath与后台参数一致的时候  进行下列逻辑
            //var flag = $.inArray(iavPath,iavPathArrays);
            iavPath = isInclude(iavPath,iavPathArrays);
            console.log(1)
            console.log(iavPath);
            if(iavPath != ""){
                console.log(iavPath);
                selectedProductId = specProductDates[iavPath].productId;
                if(specProductDates[iavPath].store > 0){
                    $("#kucun").attr("value", specProductDates[iavPath].store);
                    $("#kucun").html(specProductDates[iavPath].store);
                    $(".js_addCarOKBtn").removeClass("btn_Bghui js_btnDisable1");
                    tapFlag = false;
                    $(".js_addCarOKBtn").html('确定');
                }else{
                    $(".js_addCarOKBtn").addClass('btn_Bghui js_btnDisable1');
                    if($(".js_addCarOKBtn").hasClass("js_btnDisable1")){
                        tapFlag = true;
                    }
                    $(".js_addCarOKBtn").html('无货');
                }

                if($('#costMemberScore').length > 0){
                    $("#salePrice").attr("pprice", specProductDates[iavPath].memberPrice);
                    $("#salePrice").html(specProductDates[iavPath].memberPrice);
                    $("#costMemberScore").html(specProductDates[iavPath].memberCostScore);
                }else {
                    $("#salePrice").attr("pprice", specProductDates[iavPath].salePrice);
                    $("#salePrice").html(specProductDates[iavPath].salePrice);
                }

                if(specProductDates[iavPath].imgPath != imgBasePath){
                    $("#currentImg").attr("src", specProductDates[iavPath].imgPath);
                    $("#currentImg").html(specProductDates[iavPath].imgPath);
                }

            }else{
                $(".js_addCarOKBtn").addClass('btn_Bghui js_btnDisable1');
                if($(".js_addCarOKBtn").hasClass("js_btnDisable1")){
                    tapFlag = true;
                }
                $(".js_addCarOKBtn").html('无货');
                selectedProductId = -1;
            }


        }
    }

    //联系商家
    var oContactBoss = $('.js_contactBoss');
    var oBossInfo = $('.js_bossInfo');

    oContactBoss.hammer().on('tap', function () {
        myPub.TipTitleLayer('联系商家', '.js_bossInfo', oBossInfo.html());
        myPub.HamstopPropaga();
    })


    /**
     * 获取iavPath
     * @param {Object} ivaPath 88-89-90-92-91
     * @param {Object} ivaPathArray ["88-89-90-91-92", "88-89-90-91-93"]
     */
    function isInclude(ivaPath,ivaPathArray){
        if(ivaPathArray && ivaPath){
            var ivasLen = ivaPathArray.length;
            if(ivasLen == 0){
                return "";
            }
            var ivaPaths = ivaPath.split(','),
                ivaPathsLen = ivaPaths.length,
                ivaPathsLenjj = ivaPathsLen - 1;
            for (var i = 0; i < ivasLen; i++) {
                var	ivaPathA = ivaPathArray[i],
                    ivaPathArrays = ivaPathA.split(','),
                    ivaPathArraysLen = ivaPathArrays.length;

                var isIncludeArray = false;
                for (var j = 0; j < ivaPathsLen; j++) {
                    var isIncludeArrays = false;
                    for (var a = 0; a < ivaPathArraysLen; a++) {
                        if(ivaPaths[j]==ivaPathArrays[a]){
                            isIncludeArrays = true;
                            break;
                        }
                    }
                    if(isIncludeArrays==false){
                        break;
                    }else{
                        if(j == ivaPathsLenjj && isIncludeArrays){
                            isIncludeArray = isIncludeArrays;
                            break;
                        }
                    }
                }
                if(isIncludeArray == true){
                    return ivaPathArray[i];
                }
            }
        }
        return "";
    }



});